package com.miao.im.config;

import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import com.miao.im.support.disruptor.DisruptorEvent;
import com.miao.im.support.disruptor.DisruptorEventBus;
import com.miao.im.support.disruptor.MessageEventFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/3/18 11:38
 * @Description:
 */
@Configuration
public class DisruptorConfiguration {
    //ringbuffer大小，必须是2的N次方
    private final static int RING_BUFFER_SIZE = 1024 * 4;

    @Bean(name = "disruptor")
    public Disruptor<DisruptorEvent<?>> initDisruptor(DisruptorEventBus eventBus) {
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        EventFactory<DisruptorEvent<?>> eventFactory = new MessageEventFactory();
        Disruptor<DisruptorEvent<?>> disruptor = new Disruptor<>(eventFactory, RING_BUFFER_SIZE, threadFactory, ProducerType.SINGLE, new YieldingWaitStrategy());
        disruptor.handleEventsWithWorkerPool(eventBus);
        disruptor.start();
        return disruptor;
    }
}
